package com.qianyu.project.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qianyu.project.core.annotation.FlowBegin;
import com.qianyu.project.core.annotation.FlowEntry;
import com.qianyu.project.entity.WorkLog;
import com.qianyu.project.entity.WorkLogDetail;
import com.qianyu.project.mapper.WorkLogMapper;
import com.qianyu.project.service.IWorkLogDetailService;
import com.qianyu.project.service.IWorkLogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qianyu.project.web.controller.nyx.WorkLogDeteil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 安全日志 服务实现类
 * </p>
 *
 * @author gs
 * @since 2021-01-30
 */
@Service
public class WorkLogServiceImpl extends ServiceImpl<WorkLogMapper, WorkLog> implements IWorkLogService {

    @Autowired
    private WorkLogMapper workLogMapper;
    @Autowired
    private IWorkLogDetailService workLogDetailService;

    @Override
    public List<Map<String,Object>> getList(Map<String, String> map) {
        return workLogMapper.getList(map);
    }

    @Override
    public List<Map<String, Object>> getOrgList(Map<String, String> map) {
        return workLogMapper.getOrgList(map);
    }

    @Override
    public String getId() {
        String id=workLogMapper.getId();
        if(id == null||"".equals(id)){
            Calendar rightNow= Calendar.getInstance();
            Integer year = rightNow.get(Calendar.YEAR);
            Integer month = rightNow.get(Calendar.MONTH)+1;
            if(month<10){
                id=year+"0"+month+"0001";
            }else{
                id=year+month+"0001";
            }
        }else{
            id=(Long.parseLong(id)+1)+"";
        }
        return id;
    }

    @Transactional(rollbackFor = Exception.class)
    @FlowBegin("work_log")
    @Override
    public int save(@FlowEntry("id") WorkLog workLog, List<WorkLogDetail> workLogDetails) {
        workLog.setFlowId(1);
        workLog.setApproveStatus("1");
        System.out.println(workLog);
        save(workLog);
        for(WorkLogDetail w : workLogDetails){
            w.setRzId(workLog.getId());
        }
        workLogDetailService.saveBatch(workLogDetails);
        return 1;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateWorkLog(WorkLog workLog, List<WorkLogDetail> workLogDetails) {
        updateById(workLog);
        for(WorkLogDetail w : workLogDetails){
            w.setRzId(workLog.getId());
        }
        workLogDetailService.remove(new QueryWrapper<WorkLogDetail>().eq("rzId",workLog.getId()));
        workLogDetailService.saveBatch(workLogDetails);
    }


}
